package jchat.genral;

import jchat.interfaces.IAppManager;
import jchat.model.person;
import jchat.services.IMService;
import jchat.types.Session;


import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import chat.jdaas.R;


public class SignUp extends Activity {
	private static final int FILL_ALL_FIELDS = 0;
	protected static final int TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS = 1;
	private static final int SIGN_UP_FAILED = 2;
	private static final String IS_USER_LOGIN = "IsUserLoggedIn";
	private static final int SIGN_UP_USERNAME_CRASHED = 3;
	private static final int SIGN_UP_SUCCESSFULL = 4;
	protected static final int USERNAME_AND_PASSWORD_LENGTH_SHORT = 5;
	private static final String userkey="takekey";
	private person objperson=new person();
private static final String SERVER_RES_SIGN_UP_USERNAME_CRASHED = "2";
	private String data=null;
	    private ReadContact objcontact;
	    JSONObject objjson;
	    public String contactlist=null;
		private String settingsTAG = "AppNameSettings";

	//private EditText usernameText;
	//private EditText passwordText;
	private EditText mobiletext;
//	private EditText eMailText;
	//private EditText passwordAgainText;
	private IAppManager imService;
	private Handler handler = new Handler();
	
	private ServiceConnection mConnection = new ServiceConnection() {
        

		public void onServiceConnected(ComponentName className, IBinder service) {
         
            imService = ((IMService.IMBinder)service).getService();  
            SharedPreferences prefs = getSharedPreferences(settingsTAG, MODE_PRIVATE);
 		   boolean heel=prefs.getBoolean(IS_USER_LOGIN, false);
 		  // imService.auth=prefs.getBoolean(IS_USER_LOGIN, false);
          if (heel == true)
            {
            	Intent i = new Intent(SignUp.this, FriendList.class);																
				startActivity(i);
				SignUp.this.finish();
				
            }
       /*   SharedPreferences prefs = getSharedPreferences(settingsTAG, MODE_PRIVATE);
		   boolean heel=prefs.getBoolean(IS_USER_LOGIN, false);
           /* loginPreferences = getSharedPreferences(settingsTAG, 0);
            
              loginPrefsEditor = loginPreferences.edit();
            boolean save=loginPreferences.getBoolean(IS_USER_LOGIN, false);
            if(save==true)
            {
            	Intent i = new Intent(SignUp.this, FriendList.class);																
				startActivity(i);
				SignUp.this.finish();
            }*/
            
        }

        public void onServiceDisconnected(ComponentName className) {
           
        	imService = null;
            //Toast.makeText(SignUp.this, R.string.local_service_stopped,
              //      Toast.LENGTH_SHORT).show();
        }
    };

	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);    

	    
	               
	        setContentView(R.layout.sign_up_screen);
	        setTitle("Sign up");
	        try
	        {
	        	
	        	//Toast.makeText(getApplicationContext(), "userlogin status"+usersessn.checkLogin(), Toast.LENGTH_LONG).show();
	      //  Button signUpButton = (Button) findViewById(R.id.signUp);
	      //  Button cancelButton = (Button) findViewById(R.id.cancel_signUp);
	        //usernameText = (EditText) findViewById(R.id.userName);
	        //passwordText = (EditText) findViewById(R.id.password);  
	        //passwordAgainText = (EditText) findViewById(R.id.passwordAgain);  
	       // eMailText = (EditText) findViewById(R.id.email);
            mobiletext=(EditText)findViewById(R.id.mobile);
	        objcontact=new ReadContact(this);
		     objjson=new JSONObject();
		   objjson=objcontact.getcontects();
		   SharedPreferences prefs = getSharedPreferences(settingsTAG, MODE_PRIVATE);
		   prefs.getBoolean(IS_USER_LOGIN, false);
		   //Toast.makeText(getApplicationContext(), , Toast.LENGTH_LONG).show();
		      data=objjson.toString();
	     
	
	        
	   
	        }
	        catch(Exception e)
	        {
	        	Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
	        }
	        
	    }
	
	
	protected Dialog onCreateDialog(int id) 
	{    	
		  	
		switch (id) 
		{
			case TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS:			
				return new AlertDialog.Builder(SignUp.this)       
				.setMessage(R.string.signup_type_same_password_in_password_fields)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						/* User clicked OK so do some stuff */
					}
				})        
				.create();			
			case FILL_ALL_FIELDS:				
				return new AlertDialog.Builder(SignUp.this)       
				.setMessage(R.string.signup_fill_all_fields)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						/* User clicked OK so do some stuff */
					}
				})        
				.create();
			case SIGN_UP_FAILED:
				return new AlertDialog.Builder(SignUp.this)       
				.setMessage(R.string.signup_failed)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						/* User clicked OK so do some stuff */
					}
				})        
				.create();
			case SIGN_UP_USERNAME_CRASHED:
				return new AlertDialog.Builder(SignUp.this)       
				.setMessage(R.string.signup_username_crashed)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						/* User clicked OK so do some stuff */
					}
				})        
				.create();
			case SIGN_UP_SUCCESSFULL:
				return new AlertDialog.Builder(SignUp.this)       
				.setMessage(R.string.signup_successfull)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						finish();
					}
				})        
				.create();	
			case USERNAME_AND_PASSWORD_LENGTH_SHORT:
				return new AlertDialog.Builder(SignUp.this)       
				.setMessage(R.string.username_and_password_length_short)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						/* User clicked OK so do some stuff */
					}
				})        
				.create();
			default:
				return null;
				
		}

	
	}
	private void save()
	{
		Toast.makeText(getApplicationContext(), "Signup", Toast.LENGTH_LONG).show();
	}
	
	@Override
	protected void onResume() {
		bindService(new Intent(SignUp.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
		   
		super.onResume();
	}
	
	@Override
	protected void onPause() 
	{
		unbindService(mConnection);
		super.onPause();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater=getMenuInflater();
		   inflater.inflate(R.menu.signupmenu, menu);
	        return true;
	
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.next:
			Thread thread = new Thread(){
				String result = new String();
			
				@Override
				public void run() {
					result = imService.signUpUser(mobiletext.getText().toString(),data.toString());
					objperson.setmobile_no(mobiletext.getText().toString());
			//		contact=imService.sendcontectlist(data);
				//	save();
					
					Intent i=new Intent(userkey);
					i.putExtra(Session.KEY, result);
					sendBroadcast(i);
					handler.post(new Runnable(){

						public void run() {
							if (result!=null) {
								//Toast.makeText(getApplicationContext(), objperson.getmobile_no().toString().substring(3), Toast.LENGTH_LONG).show();
								//Toast.makeText(getApplicationContext(), Session.KEY, Toast.LENGTH_LONG).show();
								Intent i=new Intent(SignUp.this,Login.class);
								i.putExtra(Session.KEY, result);
								i.putExtra(Session.PASSWORD, objperson.getmobile_no().toString().substring(3));
								startActivity(i);
								SignUp.this.finish();
								
								//contact=imService.sendcontectlist(data);
								//Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
								
								
							//	showDialog(SIGN_UP_SUCCESSFULL);
							}
							else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
								Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
								//showDialog(SIGN_UP_USERNAME_CRASHED);
								
							}
							else  //if (result.equals(SERVER_RES_SIGN_UP_FAILED)) 
							{
								
								Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
								//showDialog(SIGN_UP_FAILED);
							}			
						}

					});
				}

			};
			thread.start();
	}
	
			
	
		
		return super.onOptionsItemSelected(item);
	}

}
